package com.vessel.decoration.mvp.presenter.mine;

import android.app.Application;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.vessel.decoration.app.data.entity.CollectResponse;
import com.vessel.decoration.mvp.contract.mine.CollectContract;
import com.vessel.decoration.mvp.ui.activity.artisan.ArtisanActivity;
import com.vessel.decoration.mvp.ui.activity.shop.ShopActivity;
import com.vessel.decoration.mvp.ui.adapter.CollectAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.vessel.decoration.app.data.entity.CollectResponse.CollectsBean.TYPE_COLLECT_ARTISAN;
import static com.vessel.decoration.app.data.entity.CollectResponse.CollectsBean.TYPE_COLLECT_SHOP;

/**
 * @author vesselzhang
 * @date 2017/11/25
 */

@ActivityScope
public class CollectPresenter extends BasePresenter<CollectContract.Model, CollectContract.View>
        implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {
    private RxErrorHandler mErrorHandler;
    private Application mApplication;
    private AppManager mAppManager;

    private CollectAdapter mAdapter;
    private List<CollectResponse.CollectsBean> mData;

    private static final int MODE_CHECK = 0;
    private static final int MODE_EDIT = 1;
    private int mEditMode = MODE_CHECK;
    private boolean isSelectAll = false;

    @Inject
    public CollectPresenter(CollectContract.Model model, CollectContract.View rootView
            , RxErrorHandler handler, Application application, AppManager appManager
            , CollectAdapter adapter, List<CollectResponse.CollectsBean> data) {
        super(model, rootView);
        this.mErrorHandler = handler;
        this.mApplication = application;
        this.mAppManager = appManager;

        this.mAdapter = adapter;
        this.mData = data;
    }

    public void collectList(boolean pullToRefresh) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", "1");
        map.put("page", "0");
        map.put("pageSize", "30");
        mModel.collectList(map)
                .doOnSubscribe(disposable -> {
                    if (pullToRefresh) mRootView.showLoading();
                })
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(
                        new ErrorHandleSubscriber<List<CollectResponse.CollectsBean>>(mErrorHandler) {
                            @Override
                            public void onNext(List<CollectResponse.CollectsBean> collectsBeans) {
                                if (pullToRefresh) {
                                    mData.clear();
                                }
                                mData.addAll(collectsBeans);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                );
    }

    public void collectOrCancel() {
        StringBuffer artisanId = new StringBuffer();
        StringBuffer shopId = new StringBuffer();
        for (CollectResponse.CollectsBean collect : mData) {
            if (collect.isSelect() && collect.getItemType() == TYPE_COLLECT_ARTISAN) {
                artisanId.append(collect.getArtisan().getArtisanId());
                artisanId.append(",");
            } else if (collect.isSelect() && collect.getItemType() == TYPE_COLLECT_SHOP) {
                shopId.append(collect.getShop().getShopId());
                shopId.append(",");
            }
        }
        if (TextUtils.isEmpty(artisanId.toString()) && TextUtils.isEmpty(shopId.toString())) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(artisanId.toString())) {
            map.put("artisanIds", artisanId.deleteCharAt(artisanId.length() - 1).toString());
        }
        if (!TextUtils.isEmpty(shopId.toString())) {
            map.put("shopIds", shopId.deleteCharAt(shopId.length() - 1).toString());
        }
        map.put("type", "1");
        mModel.collectOrCancel(map)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(
                        new ErrorHandleSubscriber<Boolean>(mErrorHandler) {
                            @Override
                            public void onNext(Boolean aBoolean) {
                                mRootView.showMessage("删除成功");
                                collectList(true);
                            }
                        }
                );
    }

    public void updateEditMode() {
        mEditMode = mEditMode == MODE_CHECK ? MODE_EDIT : MODE_CHECK;
        if (mEditMode == MODE_EDIT) {
            mRootView.updateModel(true);
        } else {
            mRootView.updateModel(false);
            clearAll();
        }
        mAdapter.setEditMode(mEditMode);
    }

    public void selectAllMain() {
        if (mAdapter == null) return;
        if (!isSelectAll) {
            for (int i = 0, j = mAdapter.getData().size(); i < j; i++) {
                mAdapter.getData().get(i).setSelect(true);
            }
            mRootView.updateBottomLayout(true, "取消全选");
            isSelectAll = true;
        } else {
            for (int i = 0, j = mAdapter.getData().size(); i < j; i++) {
                mAdapter.getData().get(i).setSelect(false);
            }
            mRootView.updateBottomLayout(false, "全选");
            isSelectAll = false;
        }
        mAdapter.notifyDataSetChanged();
    }

    private void clearAll() {
        mRootView.updateBottomLayout(false, "全选");
        isSelectAll = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mApplication = null;
    }

    @Override
    public void onLoadMoreRequested() {
        mRootView.hideLoading();
        collectList(false);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        CollectResponse.CollectsBean data = (CollectResponse.CollectsBean) adapter.getItem(position);
        if (data.getItemType() == 0) {
            Intent intent = new Intent(mApplication, ArtisanActivity.class);
            intent.putExtra("artisanId", data.getArtisan().getArtisanId());
            mRootView.launchActivity(intent);
        } else {
            Intent intent = new Intent(mApplication, ShopActivity.class);
            intent.putExtra("shopId", data.getShop().getShopId());
            mRootView.launchActivity(intent);
        }
    }
}